/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package sessions;

import entities.Artist;
import java.util.List;
import javax.ejb.LocalBean;
import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.NoResultException;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;
import webservices.ArtistResult;
import webservices.MusicWebServices;

/**
 *
 * @author Antoine Boulinguez et Shyn-Yuan Cheng
 */
@Stateless
@LocalBean
public class ArtistManager {

    @PersistenceContext(unitName = "ProjetStreamingBoulinguezCheng-ejbPU")
    private EntityManager em;

    // Create an artist if he doesn't exist yet in the DB - each artist must have a unique artist name
    public Artist createArtist(String artistName) {
        // Get an eventual existing artist
        Artist existingArtist = getArtist(artistName);

        // if he doesn't exist, create him
        if (existingArtist == null) {
            ArtistResult ar = MusicWebServices.getArtistInfos(artistName);
            Artist artist = new Artist(artistName, ar.getType(), ar.getBeginningYear());
            persist(artist);

            return artist;
        }

        return existingArtist;
    }
    
    // Get all artists
    public List<Artist> getAllArtists() {
        Query query = em.createNamedQuery("Artist.findAll");
        return query.getResultList();
    }

    // Get an artist with his artist name
    public Artist getArtist(String artistName) {
        Query query = em.createNamedQuery("Artist.getByArtistName");
        query.setParameter("artistName", artistName);

        try {
            Object result = query.getSingleResult();
            return (Artist) result;
        } catch (NoResultException e) {
            return null;
        }
    }

    public void persist(Object object) {
        em.persist(object);
    }
}
